package com.example.service.Service;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;

import com.example.service.R;

public class MusicHelper {
    private MediaPlayer mediaPlayer;
    private Context context;
    private final int[] musics = new int[]{R.raw.the_party_troll, R.raw.cyka_blyat};
    private int musicIndex = 0;
    private boolean prepared = false;

    public MusicHelper(Context context){
        this.context = context;
        createMediaPlayer();
    }

    private void createMediaPlayer(){
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }

    public void play(){
        if(mediaPlayer.isPlaying()){
            return;
        }

        if(prepared){
            mediaPlayer.start();
            return;
        }

        try{
            mediaPlayer.setDataSource(context,
                    Uri.parse("android.resource://com.example.service/" + musics[musicIndex]));
        } catch (Exception e){
            e.printStackTrace();
        }
        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                prepared = true;
            }
        });
    }

    public void pause(){
        if(!mediaPlayer.isPlaying()){
            return;
        }
        mediaPlayer.pause();
    }

    public void next(){
        musicIndex = musicIndex + 1;
        musicIndex = musicIndex % musics.length;
        destroy();
        createMediaPlayer();
        play();
    }

    public void destroy(){
        if(mediaPlayer == null){
            return;
        }
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        prepared = false;
    }
}
